#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Anton A Nesterov
# License: Apache2.0

from google.appengine.ext import db
from upload import Collection, File
from handlers import obj

import markdown

class Post(db.Model):

  title = db.StringProperty(default=u"Untitled")
  text  = db.TextProperty(default=u"Markdown")
  files = db.ReferenceProperty(Collection)
  time  = db.DateTimeProperty(auto_now=True)

  @classmethod
  def get(cls, title):
    rec = cls.all().filter("title =", title).get()

    if rec:
      html = markdown.markdown(rec.text, extensions=['extra'])
      return obj (**dict(
          title = rec.title,
          text = html,
          files =rec.files and rec.files.title or '',
          time = rec.time.strftime("%b %d %Y"),
        )
      )

    return

  @classmethod
  def put(cls, **kv):
    title = kv.get('title')
    id = kv.get('id')
    if id:
      rec = cls.get_by_id( long(id) )
    else:
      rec = cls.all().filter("title =", title).get()

    if rec:
      rec.title = title
      rec.text = kv.get('text')

    else:
      if kv.get('id'):
        del kv['id']
      files = Collection.get_or_put(title, True)
      rec = cls(files=files,**kv)

    db.put(rec)

    return

  @classmethod
  def rem(cls, id):
    post = cls.get_by_id(long(id))
    if post.files:
      File.rem_collection(post.files.key().id_or_name())
    db.delete(post)

